package net.tngou.crawler.company;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.configuration2.Configuration;

import com.alibaba.fastjson.JSONObject;

import net.tngou.crawler.util.ConfigurationUtil;

//java版计算signature签名
public class BaiduMap {
	
	
		private static  String ak;//公钥
		private static String sk;//私钥
		private static String host;
		
		static {
			Configuration config = ConfigurationUtil.config("baidu.properties");
			ak=config.getString("ak");
			sk=config.getString("sk");
			host=config.getString("host");
			
		}
		
		public static void main(String[] args) {
			JSONObject json=getLocation("22.26158,99.325288");
			System.err.println(json);
		}
        /**
         * 
         * @param name 地址名称 蓝海天地
         * @return
         * {"status":0,"result":{"location":{"lng":104.01743066728356,"lat":30.719502309068387},"precise":1,"confidence":80,"level":"商务大厦"}}
         */
        public static JSONObject getAdderss(String name) {
        	    Map<String, String> paramsMap = new LinkedHashMap<String, String>();
        	    paramsMap.put("address", name);
        	    paramsMap.put("output", "json");
        	    paramsMap.put("ak", ak);
        	    String paramsStr = toQueryString(paramsMap);
        	    String wholeStr = new String("/geocoder/v2/?" + paramsStr + sk);
//        	            
        	    try {
					String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
					String url = host+"?"+paramsStr+"&sn="+MD5(tempStr);
					URL localURL = new URL(url);
					InputStream inputStream=localURL.openStream();
					 BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));  
				       StringBuffer bs = new StringBuffer();  
				       String l = null;  
				       while((l=buffer.readLine())!=null){  
				           bs.append(l);  
				       } 
				       JSONObject json = JSONObject.parseObject(bs.toString());  
				       System.err.println(json);
				       return json;
				} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
				}
        	    JSONObject json = new JSONObject();
        	    json.put("status", 404);
				return json;
		}
        
        
        public static JSONObject getLocation (String location) {
     	    Map paramsMap = new LinkedHashMap<String, String>();
     	    paramsMap.put("location", location);
     	    paramsMap.put("output", "json");
     	    paramsMap.put("ak", ak);
     	    String paramsStr = toQueryString(paramsMap);
     	    String wholeStr = new String("/geocoder/v2/?" + paramsStr + sk);
//     	            
     	    try {
					String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
					String url = host+"?"+paramsStr+"&sn="+MD5(tempStr);
					URL localURL = new URL(url);
					InputStream inputStream=localURL.openStream();
					 BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));  
				       StringBuffer bs = new StringBuffer();  
				       String l = null;  
				       while((l=buffer.readLine())!=null){  
				           bs.append(l);  
				       } 
				       JSONObject json = JSONObject.parseObject(bs.toString());  
				       return json;
				} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
				}
     	    JSONObject json = new JSONObject();
     	    json.put("status", 404);
				return json;
		}
        
        // 对Map内所有value作utf8编码，拼接返回结果
        public static String toQueryString(Map<?, ?> data) {
                StringBuffer queryString = new StringBuffer();
                for (Entry<?, ?> pair : data.entrySet()) {
                        queryString.append(pair.getKey() + "=");
                        try {
							queryString.append(URLEncoder.encode((String) pair.getValue(),
							                "UTF-8") + "&");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
                }
                if (queryString.length() > 0) {
                        queryString.deleteCharAt(queryString.length() - 1);
                }
                return queryString.toString();
        }

        // 来自stackoverflow的MD5计算方法，调用了MessageDigest库函数，并把byte数组结果转换成16进制
        public static String MD5(String md5) {
                try {
                        java.security.MessageDigest md = java.security.MessageDigest
                                        .getInstance("MD5");
                        byte[] array = md.digest(md5.getBytes());
                        StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < array.length; ++i) {
                                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
                                                .substring(1, 3));
                        }
                        return sb.toString();
                } catch (java.security.NoSuchAlgorithmException e) {
                }
                return null;
        }
}
